import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {PagingConfig} from "@providers/paging";
import {StorageProvider} from "@providers/storage";
import {DialogProvider} from "@providers/dialog";
import {MapProvider} from "@providers/map";
import {NativeProvider} from "@providers/natives/native";
import {Util} from "@providers/util";
import {Subject} from "rxjs/Subject";
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import {WorkerProvider} from "@providers/interface/worker";

declare let AMap;

@IonicPage()
@Component({
  selector: 'page-worker-take-map',
  templateUrl: 'worker-take-map.html',
})
export class WorkerTakeMapPage {

  @ViewChild('container') mapElement: any;

  map: any;//地图对象
  marker: any;//地图标记
  markers: any = [{}];
  addressConfig: PagingConfig = new PagingConfig();
  searchTextStream: Subject<string> = new Subject<string>();//搜索流
  searchList: any[] = [];//搜索列表
  isSearch: boolean = false;//是否正在搜索
  isScrolling: boolean = true;//判断滑动到底部是否可以获取更多数据
  isFirst: boolean = true;//判断是否是第一次定位
  datas: any = [];//数据
  newDatas: any = [];//数据
  markersClick: any[] = [];//数据
  userInfo: any;
  i: number;
  datasConfig: PagingConfig = new PagingConfig();
  param = this.navParams.data;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              private mapService: MapProvider,
              private cd: ChangeDetectorRef,
              private storage: StorageProvider, private dialog: DialogProvider,
              private worker: WorkerProvider, private native: NativeProvider) {
    this.userInfo = this.storage.read("userInfo");
  }

  ionViewWillEnter() {
    this.userInfo = this.storage.read("userInfo");
    //this.datasConfig = new PagingConfig();
    this.getData(data => {
      this.datas = data;
      if (this.datas.length == 0) {
        document.getElementById("container").style.height = "100%";
        console.info("全部页面");
        document.getElementById("bottom").style.display = "none";
      } else {
        this.newDatas = this.datas[0];
        // document.getElementById("container").style.height = "75%";
        console.info("部分");
      }
      console.info(this.datas, this.datas.length);
    });
    this.loadMap();
  }

  ionViewDidLoad() {
    this.loadMap();
    //订阅搜索流
    this.searchTextStream
      .debounceTime(600)
      .distinctUntilChanged()
      .subscribe(value => {
        this.mapService.searchPlace(value, {map: ''}).subscribe(result => {
          if ("no_data" == result || Util.isNull(value)) {
            this.searchList = [];
          } else {
            if (!this.isSearch) {
              this.isSearch = true;
            }
            this.searchList = result.poiList.pois;
          }
          this.cd.detectChanges();
        });
      });
  }

  /**
   *
   * @param data
   * {
   *     "address": "烈山大道258号(工贸家电斜对面)",
   *     "distance": 29,
   *     "location": {
   *         "M": 113.37284699999998,
   *         "O": 31.717841,
   *        "lat": 31.717841,
   *         "lng": 113.372847
   *     },
   *     "name": "发源地(烈山大道旗舰店)"
   * }
   */
  dismiss(data?: any) {
    if (data) {
      this.mapService.poToAddress([data.location.lng, data.location.lat]).subscribe(value => {
        data.addressComponent = value.addressComponent;
        //this.viewCtrl.dismiss(data);
        console.info(120, data.name);
        this.getNewPoint(data);
      });
    } else {
      this.getNewPoint(data);
    }
  }

  /**
   * 加载地图
   */
  loadMap() {
    this.mapService.createMap(this.mapElement.nativeElement, {zoom: 18}).then(map => {
      this.map = map;
      //console.info("1");
      this.mapService.displayCurrentPosition().subscribe(data => {
        //console.info("1");
        if (this.param.location && this.isFirst) {
          data.position = this.param.location;
          this.isFirst = false;
        }

        // console.info(data);
        this.map.clearMap();
        /*  if (!this.marker) {
             this.marker = this.mapService.addMarker({'lng': data.position.lng, 'lat': data.position.lat});
           } else {
             this.marker.setPosition(data.position);
           }*/
        this.map.setFitView();
        this.isScrolling = true;
        this.addressConfig = new PagingConfig();
        /* //获取中心位置
         this.map.on('mapmove', () => {
           this.marker.setPosition(this.map.getCenter());
         });*/
        this.getCustomer();

      });
      this.distance()
    })
  }

  //获取查询位置的地址（中心点）
  getNewPoint(e) {
    console.info(e.location);
    this.marker = [];
    this.marker = this.mapService.addMarker({'lng': e.location.lng, 'lat': e.location.lat});
    this.map.panTo([e.location.lng, e.location.lat]);
  }

  getNewPoint2(lat, lng) {
    this.map.panTo([lng, lat]);
  }

  //获取客户位置
  getCustomer() {
    for (let i = 0; i < this.datas.length; i++) {
      this.markers.forEach((v) => {
        this.addMarkers({'lng': this.datas[i].LONGITUDE, 'lat': this.datas[i].LATITUDE}, i);
      });
    }
  }

  //根据页面内容显示页面
  markerRefresh() {
    this.getData(data => {
      this.datas = data;
      if (this.datas.length == 0) {
        this.map.clearMap();
        document.getElementById("container").style.height = "100%";
        console.info("全部页面");
        document.getElementById("bottom").style.display = "none";
      } else {
        this.newDatas = this.datas[0];
        // document.getElementById("container").style.height = "75%";
        console.info("部分");
      }
      console.info("执行", this.datas, this.datas.length);
      this.map.clearMap();
      this.getCustomer();
    });
  }

  /**
   * 获取数据
   * @param pagingConfig 分页
   * @param fn 方法
   * @param errFun 反生错误后执行
   */
  private getData(fn: (value) => void, errFun?: () => void) {
    this.worker.selectSOrder({
      "STATUSID": "GRABED",
      "PARTYID": this.userInfo.PARTYID,
      //"SERVICETYPEID": "0",
      "ZB": "HQZB",
      "skip": 0,
      "limit": 50
    }).then(message => {
      let data = message || [];
      data.forEach((v) => {
        let d: Date = new Date(v.THRUTIME);
        if (!isNaN(v.THRUTIME)) {
          v.THRUTIME = Util.dateFormat(d, "yyyy-MM-dd")
        }

      });
      fn(data);
    }).catch(e => {
      if (errFun) {
        errFun();
      }
    });
  }

  /***
   * 比例尺计算
   * @param dis
   * @returns {number}
   */
  scale(dis: number) {
    if (dis <= 10) return 19;
    else if (dis <= 25) return 18;
    else if (dis <= 50) return 17;
    else if (dis <= 100) return 16;
    else if (dis <= 200) return 15;
    else if (dis <= 500) return 14;
    else if (dis <= 1000) return 13;
    else if (dis <= 2000) return 12;
    else if (dis <= 5000) return 11;
    else if (dis <= 10000) return 10;
    else if (dis <= 20000) return 9;
    else if (dis <= 30000) return 8;
    else if (dis <= 50000) return 7;
    else if (dis <= 100000) return 6;
    else if (dis <= 200000) return 5;
    else if (dis <= 500000) return 4;
    else if (dis <= 1000000) return 3;
    else if (dis > 1000000) return 2;
    return 20;
  }

  /**
   * 排序
   * @param disArray
   */
  sort(disArray) {
    for (let i = 0; i < disArray.length - 1; i++) {
      for (let j = i + 1; j < disArray.length; j++) {
        if (disArray[i] > disArray[j]) {
          let temp = disArray[i];
          disArray[i] = disArray[j];
          disArray[j] = temp;
        }
      }
    }
    console.info(disArray);
  }

  /**
   * 中心点到客户距离计算
   *
   */
  distance() {
    let center = this.map.getCenter();
    let disArray = []
    this.datas.forEach((v) => {
      let dis = this.native.getGreatCircleDistance(center.lng, center.lat, v.LONGITUDE, v.LATITUDE) / 4;
      disArray.push(dis)
    });
    this.sort(disArray);
    for (let i = 0; i < this.datas.length; i++) {
      if (i >= 9) {
        let sc = this.scale(disArray[9]);
        this.map.setZoomAndCenter(sc, [center.lng, center.lat]);
        break;
      } else {
        let sc = this.scale(disArray[this.datas.length - 1]);
        console.info(sc);
        this.map.setZoomAndCenter(sc, [center.lng, center.lat]);
        break;
      }
    }
    console.info(this.map.getZoom())
  }

  /**添加客户坐标和绑定坐标点击事件
   *
   *传入值为json{map: this.map,
   *                  icon: markers.icon,
   *                  position: [markers.position[0], markers.position[1]],
   *            }
   *
   */
  addMarkers(position, i?: any): any {
    let lngX = position.lng;
    let latY = position.lat;
    let markerOption = Object.assign({
      map: this.map,
      icon: new AMap.Icon({
        image: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b' + (i + 1) + '.png',
        size: new AMap.Size(31, 31),//图层大小
        imageSize: new AMap.Size(19, 31)  //图标大小
      }),
      clickable: true,//可点击
      // draggable:true,//可移动
      position: [lngX, latY],
    });

    //点击事件绑定
    this.markersClick[i] = new AMap.Marker(markerOption);
    this.markersClick[i].on('click', (datas) => {
      // console.info(lngX);
      this.i = i;
      this.newDatas = this.datas[i];
      this.map.panTo([lngX, latY]);
      console.info("newDatas", this.newDatas, this.markersClick);
    });
    return this.markersClick;
  }

  /**
   * 接单
   * @param data
   * @param i
   */
  submit(data: any, i: number) {
    this.dialog.showConfirm(() => {
      this.dialog.showLoading();
      this.worker.dispatch({
        'id': data.ID,
        'partyId': this.userInfo.PARTYID,
        "worker_name": this.userInfo.USERNAME,
        "dispatcher": this.userInfo.USERNAME,
        "type": 'fw'
      }).then(length => {
        this.dialog.hideLoading();
        // this.dialog.showAlert("抢单成功！");
        //删除标记和绑定
        length = this.datas.length;
        if (length > 0) {
          console.info(this.markersClick[this.i]);
          this.markersClick[this.i].setMap(null);
          this.markerRefresh();
          console.info("成功删除标记");
          //计数
          length--;
          this.i--;
          console.info("还剩：" + length);
        }
        //this.markerRefresh();
        // 地图变100%
        if (length == 0) {
          document.getElementById("container").style.height = "100%";
          document.getElementById("bottom").style.display = "none";
        }
        this.datas.splice(i, 1);
      }).catch(e => {
        this.dialog.hideLoading();
        this.dialog.showAlert('该订单已经被其他人抢了，您可以选择其他订单！');
      });
    }, "是否确定抢单？");
  }

  /**
   * 搜索事件
   * @param data
   */
  search(data: string) {
    this.searchTextStream.next(data);
    console.info(110, data);
  }

  /**
   * 输入框获得焦点时调用
   */
  changeIsSearch() {
    this.isSearch = true;
  }

  /**
   * 下拉刷新
   * @param refresher
   */
  doRefresh(refresher?: any) {
    if (refresher) {
      setTimeout(() => {
        refresher.complete();
      }, 500);
    }
    console.info("完成");
  }

  //语音提示
  phoneticHints() {

  }

}
